import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from openai import OpenAI
from typing import List, Dict, Any

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

app = FastAPI(title="Model Evaluator API", version="1.0.0")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class ImageQueryRequest(BaseModel):
    image_url: str
    query: str

class ImageQueryResponse(BaseModel):
    success: bool
    result: str
    error: str = None

@app.get("/")
async def root():
    return {"message": "Model Evaluator API is running"}

@app.post("/api/image-query", response_model=ImageQueryResponse)
async def image_query(request: ImageQueryRequest):
    """
    调用阿里云通义千问API进行图像查询
    """
    try:
        logger.info(f"Received image query request - Image URL: {request.image_url}, Query: {request.query}")
        
        # 检查API Key是否配置
        api_key = os.getenv("DASHSCOPE_API_KEY")
        if not api_key:
            logger.error("DASHSCOPE_API_KEY environment variable not set")
            return ImageQueryResponse(
                success=False,
                result="",
                error="API Key not configured. Please set DASHSCOPE_API_KEY environment variable."
            )
        
        # 创建OpenAI客户端
        client = OpenAI(
            api_key=os.getenv("DASHSCOPE_API_KEY"),  # 从环境变量获取API Key
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )
        
        # 构建请求消息
        messages = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": request.image_url}
                    },
                    {
                        "type": "text", 
                        "text": request.query
                    }
                ]
            }
        ]
        
        logger.info("Calling OpenAI API with messages")
        
        # 调用API
        completion = client.chat.completions.create(
            model="qwen-vl-plus",
            messages=messages
        )
        
        # 获取响应
        result = completion.model_dump_json()
        logger.info("API call successful")
        
        return ImageQueryResponse(
            success=True,
            result=result
        )
        
    except Exception as e:
        logger.error(f"Error in image query: {str(e)}")
        return ImageQueryResponse(
            success=False,
            result="",
            error=str(e)
        )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000) 